<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/13
 * Time: 11:36
 */

/**
 * 自动加载函数
 * @param $className
 */
function loadClass($className)
{
    $fileName = '';
    $namespace = '';

    // Sets the include path as the "src" directory
    $includePath = dirname(__FILE__).DIRECTORY_SEPARATOR;

    if (false !== ($lastNsPos = strripos($className, '\\'))) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    $fullFileName = $includePath . DIRECTORY_SEPARATOR . $fileName;

    if (file_exists($fullFileName)) {
        require $fullFileName;
    } else {
        sp_error_log("Class {$className} does not exist.\r\nFullFileName:{$fullFileName}.\r\n");
    }
}

/**
 * 写入错误日志
 * @param $info
 */
function sp_error_log($info)
{
    log_append($info, ROOT_PATH.'logs/error/'.date('YmdH').'.log');
}

/**
 * 添加到日志文件
 * @param $info
 * @param $file
 * @param int $line
 */
function log_append($info, $file, $line = 0)
{
    $line = $line ? $line : (isset(\lib\App::$config['log_max_line']) ? \lib\App::$config['log_max_line'] : 0);
    if(!file_exists($file)){
        touch($file);
        chmod($file, 0755);
    }

    if($line > 0) {
        preg_match_all('/.*/', file_get_contents($file), $matches);
        if(count($matches[0]) > $line) {
            $newInfo = date('Y-m-d H:i:s')."    $info\n";
            for($i = 0; $i < $line; $i++) {
                $matches[0][$i] && $newInfo .= $matches[0][$i]."\n";
            }
        }
    }
    $newInfo = isset($newInfo) ? $newInfo : date('Y-m-d H:i:s')."    $info\n".file_get_contents($file);
    file_put_contents($file, $newInfo);
}

/**
 * 返回域名
 * @return string
 */
function getSiteUrl()
{
    return SITE_URL;
}

/**
 * 读取配置文件
 * @param $key
 * @return array|bool|mixed
 */
function C($key = null)
{
    $config_root = PROJECT_ROOT.'Application/Common/Conf/';
    $config = require $config_root.'config.php';
    if($config['LOAD_EXT_CONFIG']){
        $ext_config = explode(',',$config['LOAD_EXT_CONFIG']);
        foreach($ext_config as $item){
            $tmp_file = $config_root.trim($item).'.php';
            if(file_exists($tmp_file)){
                $tmp = require $tmp_file;
                if(is_array($tmp)){
                    $config = array_merge($config, $tmp);
                }
            }
        }
    }

    if(!$key){
        return $config;
    } else {
        return $config[$key] ? $config[$key] : false;
    }
}

/**
 * 写入猎单宝订单日志
 * @param array $order_info 订单信息
 * @param $tips
 * @param $do_user
 * @param null $change_info
 * @param int $time
 * @param array $info
 * @return bool
 */
function LdbOrderLog($order_info, $tips, $do_user, $change_info = null, $time = 0, $info = array()){
    $tips_arr = C('ORDER_LOG_TIPS');
    if($do_user==3){
        $do_user=0;
    }
    $data = array(
        'order_sn'=>$order_info['order_sn'],  // 订单号
        'action_tips'=>$tips_arr[$tips],    // 操作说明
        'log_time'=>$time ? $time : time(),         // 操作时间戳
        'do_user_role'=>$do_user,        // 操作用户类型 1:买家 2：卖家 0：管理
        'do_user_id'=>0,
        'order_status'=>$order_info['order_status'] ? $order_info['order_status'] : 0,
        'shipping_status'=>$order_info['shipping_status'] ? $order_info['shipping_status'] : 0,
        'delay_apply_status'=>$order_info['delay_apply_status'] ? $order_info['delay_apply_status'] : 0,
        'log_extra'=>isset($info['log_extra']) ? $info['log_extra'] : '',
    );
    if($change_info){
        $data['log_extra']=json_encode($change_info);
    }
    if($do_user==0){
        $data['action_note']= '定时处理在'.date('Y-m-d H:i:s',time()).$tips_arr[$tips];
    }
    $model = new \lib\Model();
    $model->table('ldb_order_log');
    if($model->create($data) && $model->add())
    {
        return true;
    }
    else
    {
        return false;
    }

}

/**
 * 邮件发送函数封装
 * $toemail 接收邮件的用户邮箱
 * $order 采购单或者竞标单
 * $info 采购商信息
 * $type 发送类型
 * 1：有新的报价（默认） 2：已中标 3：确认采购 4：过期未付款自动取消订单
 */
function sendemail($toemail,$order,$type='1',$info=''){
    $model = new \lib\LdbOrder();
    if(!$toemail){
        return false;
    }
    if($type!=2){
        $find=$model->where(array('order_sn'=>$order))->field('demand_user_id')->find();
        $types=member_type($find['demand_user_id']);
    }
    if($type==1){
        $title='您的采购单'.$order.'有新的报价，速去洽谈';
        $content='
                    <p style="color: #434343; padding-bottom: 25px; line-height: 23px; font-size: 12px;">您的采购单<a style="color: #23a8f6;" href="http://www.ichunt.com/Ldb/Purchase/detail/order_sn'.$order.'" target="_blink">'.$order.'</a>有人报价，您可以随时进入订单详情页面查看订单的后续处理情况。
                     ';
    }

    if($type==2){
        $find = $model->table('bid_record')->where(array('bid_id'=>$order))->field('user_id')->find();
        $type = member_type($find['user_id']);
        $title='您的竞标单'.$order.'已中标，速去洽谈';
        $content='
                      <p style="color: #434343; padding-bottom: 25px; line-height: 23px; font-size: 12px;">您的竞标单<a style="color: #23a8f6;" href="http://www.ichunt.com/Ldb/Sales/detail/order_sn'.$order.'" target="_blink">'.$order.'</a>已中标，您可以随时进入订单详情页面查看订单的后续处理情况。

                      <br>采购商姓名：'.$info['name'].'，联系电话：'.$info['phone'].'。
                      ';
    }

    if($type==3){
        $title='您的采购单'.$order.'已定标，请尽快付款';
        $content='
                       <p style="color: #434343; padding-bottom: 25px; line-height: 23px; font-size: 12px;">您的采购单<a style="color: #23a8f6;" href="http://www.ichunt.com/Ldb/Purchase/detail/order_sn'.$order.'" target="_blink">'.$order.'</a>已定标、未支付，请尽快进入订单详情页面查看订单的后续处理情况。请在1个工作日内付款，过期自动取消订单。
                      ';
    }

    if($type==4){
        $title='您的采购单'.$order.'已自动取消';
        $content='
                      <p style="color: #434343; padding-bottom: 25px; line-height: 23px; font-size: 12px;">您的采购单<a style="color: #23a8f6;" href="http://www.ichunt.com/Ldb/Purchase/detail/order_sn'.$order.'" target="_blink">'.$order.'</a>过期未付款，已自动取消。若要重新采购，请再次发布<a href="http://www,ichunt.com/Ldb/Purchase/index.html">采购需求</a>。
                      ';
    }

    if($types=='0'){
        $url='http://www.ichunt.com/Home/Purchase/index.html';
    }if($types=='1'){
        $url='http://www.ichunt.com/Home/Sale/batchAddGoods.html';
    }
    $html='<body style="font-family:"Open Sans",Arial,"Hiragino Sans GB","Microsoft YaHei","微软雅黑","STHeiti","WenQuanYi Micro Hei",SimSun,sans-serif; text-decoration: none;}
                body,html{ width: 100%; height: 100%; padding: 0; margin: 0; color: #252525; font-size: 12px;">
                    <div style="width:736px;min-width: 736px; max-width: 736px; padding: 0 32px; margin:0 auto; border-top: 4px solid #23a8f6; border-radius: 2px; box-shadow: 0 2px 3px #eeeeee;
                    -webkit-box-shadow: 0 2px 3px #EEEEEE;">
                        <div style="height: 61px; padding-top: 38px; border-bottom: 2px solid #dddcdc;">
                            <ul style="float: right; text-align: right;">
                                <li style="display: inline-block; list-style: none; color: #434343;"><a href="http://www.ichunt.com/" target="_blink" style="color: #23a8f6; font-weight: bold; margin-right: 18px; margin-left: 15px;">猎芯网</a><span style="color: #c4c4c4;">|</span></li>
                                <li style="display: inline-block; list-style: none; color: #434343;"><a href="'.$url.'" target="_blink" style="color: #23a8f6; font-weight: bold; margin-right: 18px; margin-left: 15px;">会员中心</a></li>
                                <li style="display: inline-block; list-style: none; color: #434343;">客服电话：<b style="font-weight: bold; font-size: 16px;">0755-88914841</b></li>
                            </ul>
                            <div style="float: left;">
                            <a href="http://www.ichunt.com/" target="_blink">
                                <img width="300px" src="http://www.ichunt.com/Public/Home/images/logo.png">
                            </a>
                            </div>
                        </div>
                        <div style="min-height: 480px; *height: 480px;">
                            <h1 style="font-weight: bold; color: #434343; padding: 20px 0; font-size: 12px;">亲爱的会员：</h1>
                            '.$content.'
                            <br>安全提醒：猎芯网不会以付款异常、系统升级等为由要求您退款或再次支付，同时也不会发送虚拟网址、中奖、抽奖的短信让您点击进入；请您不要将银行卡资料、验证码、个人资料等提供他人，谨防诈骗！遇此情况请及时联系客服人员或报警。为了您的会员账户安全，建议您不要用公共场所的网络记住您的登录账号及密码。</p>
                            <p style="color: #434343; padding-bottom: 25px; line-height: 23px; font-size: 12px;">防诈骗提醒须知<br>请认准唯一官方网址：<a style="color: #23a8f6;" href="http://www.ichunt.com/" target="_blink">www.ichunt.com</a></p>
                        </div>
                        <dl style="height: 79px; padding: 15px 0; border-bottom: 1px dashed #dadada;  border-top: 1px dashed #dadada;">
                            <dt style="float: left; height: 79px; width: 80px;">
                            <img style="border: none; padding: 0; margin: 0; display: block; height: 77px; width: 77px; border: 1px solid #eeeeee;  border-radius:3px;" src="http://www.ichunt.com/Public/Home/images/code.jpg">
                            </dt>
                            <dd>
                                <p><b>了解更多IC资讯、猎芯活动，关注猎芯网</b></p>
                                <p>猎芯网( www.ichunt.com）电子元器件全产业链B2B电商平台</p>
                            </dd>
                        </dl>
                        <div style="padding: 20px 0;">
                            <p style="color: #515151;">此邮件为猎芯网系统自动发出，请勿直接回复</p>
                            <p style="color: #bababa;">深圳市猎芯科技有限公司   粤ICP备15024702号-1 Copyright®深圳市猎芯科技有限公司 </p>
                        </div>
                    </div>
                </body>';
    $Email = new \lib\Email();
    $send = $Email->send($toemail,$title,$html);
    return $send;
}

/**
 * 提交POST数据
 * 如果使用Curl 你需要改一改你的php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 *
 * @param   string   服务接口地址
 * @param   mixed    提交数据
 * @param   array    http头信息
 * @param   boolean  是否SSL传输
 * @return  mixed    返回结果
 **/
function http_post($gateway_url, $req_data, $optional_headers = null, $isSSL = false) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $gateway_url);                //配置网关地址
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);                          //设置post提交
    curl_setopt($ch, CURLOPT_POSTFIELDS, $req_data);            //post传输数据
    if ($optional_headers !== null){
        curl_setopt($ch, CURLOPT_HTTPHEADER, $optional_headers);
    }
    else{
        curl_setopt($ch, CURLOPT_HEADER, 0);                        //过滤HTTP头
    }
    if($isSSL){
        curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1); //SSL版本
    }
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

/**
 * 模型
 * @param $tableName
 * @return \lib\Model
 */
function M($tableName)
{
    $model = new \lib\Model();
    $model->table($tableName);
    return $model;
}